package com.houtai.msmservice.controller;

import com.aliyuncs.utils.StringUtils;
import com.houtai.commonutils.Result;
import com.houtai.msmservice.service.MsmService;
import com.houtai.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmController
 * @Description 短信验证
 * @Author xst
 * @Date 2022/12/3 2:31
 * @Version 1.0
 **/
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public Result sendMsm(@Valid @PathVariable String phone){
        //从redis获取验证码。获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //如果redis获取不到，进行阿里云发送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //调用service的发送短信方法
        boolean isSend = msmService.send(param,phone);
        if(isSend){
            //发送成功，放进redis
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            //System.out.println(phone +',' + code);
            return Result.ok().data("code",code);
        }else{
            return Result.error().message("短信发送失败");
        }

    }

}
